<?php

namespace business\search\services;

use business\base\services\BasicCategoryService;
use business\base\services\BspShowForestService;

class BaseUtil
{

    public static function  getResultCategory($faceComponent)
    {
        $faces = $faceComponent->getFacets();
        $level1FacetValues = null;
        $level2FacetValues = null;
        foreach ($faces as $key => $face) {
            if ("operationCategoryCode1" == $key) {
                $level1FacetValues = $face->getValues();
                continue;
            }
            if ("operationCategoryCode2" == $key) {
                $level2FacetValues = $face->getValues();
            }
        }
        $categoryService = new BspShowForestService();
        $level1Codes = array_keys($level1FacetValues);
        $level1BaseCategoryArray = $categoryService->getCategoryModelListByCodes($level1Codes);
        $level2Code = array_keys($level2FacetValues);
        $level2BaseCategoryArray = $categoryService->getCategoryModelListByCodes($level2Code);
        $level1SearchCategoryArray = self::basicCategoryToSearchCategoryArray($level1BaseCategoryArray, $level1FacetValues);
        $level2SearchCategoryArray = self::basicCategoryToSearchCategoryArray($level2BaseCategoryArray, $level2FacetValues);
        foreach ($level1SearchCategoryArray as &$level1SearchCategoryModel) {
            $level2Nodes = [];
            foreach ($level2SearchCategoryArray as $level2SearchCategory) {
                if ($level1SearchCategoryModel["code"] == $level2SearchCategory["parentCode"]) {
                    array_push($level2Nodes, $level2SearchCategory);
                }
            }
            usort($level2Nodes, function ($node, $otherNode) {
                if ($node["count"] == $otherNode["count"]) {
                    return 0;
                }
                return $node["count"] > $otherNode["count"] ? -1 : 1;
            });
            $level1SearchCategoryModel["childrenList"] = $level2Nodes;
        }

        usort($level1SearchCategoryArray, function ($node, $otherNode) {
            if ($node["count"] == $otherNode["count"]) {
                return 0;
            }
            return $node["count"] > $otherNode["count"] ? -1 : 1;
        });

        return $level1SearchCategoryArray;
    }

    private static function  basicCategoryToSearchCategoryArray($categories, $codesMap = null)
    {
        $result = [];
        if (is_null($categories)) {
            return $result;
        }
        foreach ($categories as $category) {
            $searchCategoryVO = self::buildSearchCategoryArray($codesMap, $category);
            // $searchCategoryVO["childrenList"]=$category->$childCategoryList;
            array_push($result, $searchCategoryVO);
        }
        return $result;
    }

    public static function getOperationCategoryList()
    {
        $categoryService = new BspShowForestService();
        $rootCategoryArray = $categoryService->getCategoryRootHierarchy();
        $result = [];
        foreach ($rootCategoryArray as $rootCategory) {
            $rootSearchCategory = self::buildSearchCategoryArray(null, $rootCategory);
            $rootSearchCategory["childrenList"] = self::basicCategoryToSearchCategoryArray($rootCategory->childCategoryList, null);
            array_push($result, $rootSearchCategory);
        }
        return $result;
    }

    public static function  getResultLvl3Category($facetFields, $lvl2code, $lvl1Code)
    {
        $level3FacetValues = null;
        foreach ($facetFields as $key => $face) {
            if ("operationCategoryCode3" == $key) {
                $level3FacetValues = $face->getValues();
                break;
            }
        }
        $categoryService = new BspShowForestService();
        $level3Codes = array_keys($level3FacetValues);
        $level3BaseCategoryArray = $categoryService->getCategoryModelListByCodes($level3Codes);
        $level3SearchCategoryArray = self::basicCategoryToSearchCategoryArray($level3BaseCategoryArray, $level3FacetValues);
        $categoryCacheModel = $categoryService->getCategoryCacheModel();
        foreach ($level3SearchCategoryArray as $index => $level3SearchCategory) {
            if (!is_null($lvl2code)) {
                if ($lvl2code != $level3SearchCategory["parentCode"]) {
                    unset($level3SearchCategoryArray[$index]);
                }
            } else {
                if (!is_null($lvl1Code)) {
                    $level2CategoryModel = $categoryCacheModel[$level3SearchCategory["parentCode"]];
                    if (!is_null($level2CategoryModel) && $lvl1Code != $level2CategoryModel->parentCode) {
                        unset($level3SearchCategoryArray[$index]);
                    }
                }
            }
        }

        usort($level3SearchCategoryArray, function ($node, $otherNode) {
            if ($node["count"] == $otherNode["count"]) {
                return 0;
            }
            return $node["count"] > $otherNode["count"] ? -1 : 1;
        });

        //添加levelCode1
        foreach ($level3SearchCategoryArray as &$level3Category) {
            $level2Code = $level3Category["parentCode"];
            $level3Category["ancientCode"] = $categoryService->getParentDirectoryName($level2Code);
        }

        return $level3SearchCategoryArray;
    }

    /**
     * @param $codesMap
     * @param $category
     * @return array
     */
    private static function buildSearchCategoryArray($codesMap, $category)
    {
        if (is_null($category)) {
            return null;
        }
        $searchCategoryVO = [];
        $searchCategoryVO["code"] = $category->categoryCode;
        $searchCategoryVO["name"] = $category->categoryName;
        $searchCategoryVO["parentCode"] = $category->parentCode;
        if (!is_null($codesMap)) {
            $searchCategoryVO["count"] = $codesMap[$category->categoryCode];
        }
        $searchCategoryVO["pinyin"] = $category->directoryName;
        return $searchCategoryVO;
    }

    public static function getAllSubStr($keyWord)
    {
        if (empty($keyWord)) {
            return null;
        }
        $subStrArray = [];
        $len = mb_strlen($keyWord, "utf-8");
        for ($i = 0; $i < $len - 1; $i++) {
            for ($j = $i + 2; $j <= $len; $j++) {
                array_push($subStrArray, mb_substr($keyWord, $i, $j, "utf-8"));
            }
        }
        return $subStrArray;
    }


    /**
     * 根据codes获取所有3层的basicCategory和OperationCategory
     * @param $categoryCodes
     * @return array
     */
    public static function getAllBasicAndOperationCategoriesByCodes($categoryCodes)
    {

        if (!is_array($categoryCodes)) {
            $categoryCodes = [$categoryCodes];
        }

        $data = [
            'basicCategoryCode' => [],
            'basicCategoryCode1' => [],
            'basicCategoryCode2' => [],
            'basicCategoryCode3' => [],
            'basicCategoryName' => [],
            'basicCategoryName1' => [],
            'basicCategoryName2' => [],
            'basicCategoryName3' => [],

            //增加只保存最多前面3个行业分类字段
            'basicCategoryCodeFirst3' => [],
            'basicCategoryNameFirst3' => [],

            'operationCategoryCode' => [],
            'operationCategoryCode1' => [],
            'operationCategoryCode2' => [],
            'operationCategoryCode3' => [],
            'operationCategoryName' => [],
            'operationCategoryName1' => [],
            'operationCategoryName2' => [],
            'operationCategoryName3' => [],
        ];

        //1.获取所有层级的基础分类
        $basicCategoryService = new BasicCategoryService();
        $data['basicCategoryCode'] = $categoryCodes;
        $data['basicCategoryCode3'] = $categoryCodes;
        $first3Count = 0;
        foreach ($categoryCodes as $categoryCode) {
            //1.1获取3级分类
            $basicCategoryName = $basicCategoryService->getCategoryNameByCode($categoryCode);
            array_push($data['basicCategoryName'], $basicCategoryName);
            array_push($data['basicCategoryName3'], $basicCategoryName);
            if($first3Count < 3){
                array_push($data['basicCategoryCodeFirst3'], $categoryCode);
                array_push($data['basicCategoryNameFirst3'], $basicCategoryName);
                $first3Count++;
            }

            //1.2获取基础二级分类
            $thirdCategory = $basicCategoryService->getCategoryByCode($categoryCode);
            $secondCategoryCode = null;
            if(!empty($thirdCategory)){
                $secondCategoryCode = $thirdCategory->parentCode;
                array_push($data['basicCategoryCode2'], $secondCategoryCode);
                $secondCategoryName = $basicCategoryService->getCategoryNameByCode($secondCategoryCode);
                array_push($data['basicCategoryName2'], !empty($secondCategoryName) ? $secondCategoryName : "");
            }
            //1.3获取基础一级分类
            if(!empty($secondCategoryCode)){
                $firstCategoryCode = null;
                $secondCategory = $basicCategoryService->getCategoryByCode($secondCategoryCode);
                if(!empty($secondCategory)){
                    $firstCategoryCode = $secondCategory->parentCode;
                    array_push($data['basicCategoryCode1'], $firstCategoryCode);
                    $firstCategoryName = $basicCategoryService->getCategoryNameByCode($firstCategoryCode);
                    array_push($data['basicCategoryName1'], !empty($firstCategoryName) ? $firstCategoryName : "");
                }
            }
        }

        //2.获取所有层级的运营分类
        $operationCategoryService = new BspShowForestService();
        foreach ($categoryCodes as $basicCode) {
            //2.1获取三级运营分类
            $operationCode = $operationCategoryService->getCategoryCodeByBasicCategoryCode($basicCode);
            $operationCode = !empty($operationCode) ? $operationCode : "";
            array_push($data['operationCategoryCode'], $operationCode);
            array_push($data['operationCategoryCode3'], $operationCode);
            $operationName = $operationCategoryService->getCategoryNameByCode($operationCode);
            $operationName = !empty($operationName) ? $operationName : "";
            array_push($data['operationCategoryName'], $operationName);
            array_push($data['operationCategoryName3'], $operationName);
            //2.2获取二级运营分类
            $thirdOpeCategory = $operationCategoryService->getCategoryByCode($operationCode);
            $secondOpeCategoryCode = null;
            if(!empty($thirdOpeCategory)){
                $secondOpeCategoryCode = $thirdOpeCategory->parentCode;
                array_push($data['operationCategoryCode2'], $secondOpeCategoryCode);
                $secondOpeCategoryName = $operationCategoryService->getCategoryNameByCode($secondOpeCategoryCode);
                array_push($data['operationCategoryName2'], !empty($secondOpeCategoryName) ? $secondOpeCategoryName : "");
            }
            //2.3获取一级运营分类
            if(!empty($secondOpeCategoryCode)){
                $firstOpeCategoryCode = null;
                $secondOpeCategory = $operationCategoryService->getCategoryByCode($secondOpeCategoryCode);
                if(!empty($secondOpeCategory)){
                    $firstOpeCategoryCode = $secondOpeCategory->parentCode;
                    array_push($data['operationCategoryCode1'], $firstOpeCategoryCode);
                    $firstOpeCategoryName = $operationCategoryService->getCategoryNameByCode($firstOpeCategoryCode);
                    array_push($data['operationCategoryName1'], !empty($firstOpeCategoryName) ? $firstOpeCategoryName : "");
                }
            }
        }

        //3.去重
        foreach($data as &$item){
            //array_flip(): only flip STRING and INTEGER values
            if(!empty($item) && is_array($item)){
                $item = array_flip($item);
                $item = array_flip($item);
                $item = array_values($item);
            }
        }

        return $data;
    }

    // 计算分类排名分数
    public static function calCategoryCodeRank($categoryCodes)
    {
        if (empty($categoryCodes)) {
            return [];
        }
        $categoryCodes = array_unique($categoryCodes);
        $defaultScore = [120,80,60,40,20,10];
        $len = count($categoryCodes);
        if ($len < count($defaultScore)) {
            $scores = array_slice($defaultScore,0,$len);
        } else {
            $scores = array_pad($defaultScore,$len,1);
        }
        return array_combine($categoryCodes,$scores);
    }


    /**
     * 根据codes获取所有3层的basicCategory(实际取operationCategory)
     * @param $categoryCodes
     * @return array
     */
    public static function getAllBasicCategoriesByCodes($categoryCodes)
    {

        if (!is_array($categoryCodes)) {
            $categoryCodes = [$categoryCodes];
        }

        $data = [
            'sjBasicCategoryCode1' => [],
            'sjBasicCategoryCode2' => [],
            'sjBasicCategoryCode3' => [],
            'sjBasicCategoryName1' => [],
            'sjBasicCategoryName2' => [],
            'sjBasicCategoryName3' => [],
        ];

        //1.获取所有层级的基础分类
        $basicCategoryService = new BasicCategoryService();
        $data['sjBasicCategoryCode3'] = $categoryCodes;
        foreach ($categoryCodes as $categoryCode) {
            //1.1获取3级分类
            $basicCategoryName = $basicCategoryService->getCategoryNameByCode($categoryCode);
            array_push($data['sjBasicCategoryName3'], $basicCategoryName);
            //1.2获取基础二级分类
            $thirdCategory = $basicCategoryService->getCategoryByCode($categoryCode);
            $secondCategoryCode = null;
            if(!empty($thirdCategory)){
                $secondCategoryCode = $thirdCategory->parentCode;
                array_push($data['sjBasicCategoryCode2'], $secondCategoryCode);
                $secondCategoryName = $basicCategoryService->getCategoryNameByCode($secondCategoryCode);
                array_push($data['sjBasicCategoryName2'], $secondCategoryName);
            }
            //1.3获取基础一级分类
            if(!empty($secondCategoryCode)){
                $firstCategoryCode = null;
                $secondCategory = $basicCategoryService->getCategoryByCode($secondCategoryCode);
                if(!empty($secondCategory)){
                    $firstCategoryCode = $secondCategory->parentCode;
                    array_push($data['sjBasicCategoryCode1'], $firstCategoryCode);
                    $firstCategoryName = $basicCategoryService->getCategoryNameByCode($firstCategoryCode);
                    array_push($data['sjBasicCategoryName1'], $firstCategoryName);
                }
            }
        }

        //3.去重
        foreach($data as &$item){
            //array_flip(): only flip STRING and INTEGER values
            if(!empty($item) && is_array($item)){
                $item = array_flip($item);
                $item = array_flip($item);
                $item = array_values($item);
            }
        }

        return $data;
    }

}